(function(){

query = function(selector, context) {
	return this instanceof query ?
		this.init(selector, context) :
		new query(selector, context);
};
query.prototype.init = function(selector, context) {
	var re = new RegExp("([a-z0-9]*)([\.#:]*)(.*|$)", "ig");
	var match = re.exec(selector);
	var conditions = [];

	if (match[2] == "#")	conditions.push(["id", '=', match[3]]);
	else if(match[2] == ".")	conditions.push(["className", '~=', match[3]]);
	else if(match[2] == ":")	conditions.push(["type", '=', match[3]]);

	var s = match[3].replace(/\[(.*)\]/g,'$1').split('@');
	map(s, function(v){
		var cc = null;
		if (cc=/([\w]+)([=^%!$~]+)(.*)$/.exec(v)){
			conditions.push([cc[1], cc[2], cc[3]]);
		}
	});

	if (context && context.constructor == String){
		context = query(context).get(0);
	}
	var list = conditions[0] && conditions[0][0] == "id" ? [id(conditions[0][2])] : tag(match[1] || "*");
	if (!list || !list.length)	return [];
	this.elements = [];
	this.elements = grep(list, function(o){
		var r = true;
		for (var i=0; i<conditions.length; i++){
			var pattern = null;
			if(conditions[i][1] == '=') {
				pattern = new RegExp('^('+conditions[i][2]+')$', 'i');
			} else if(conditions[i][1] == '^=') {
				pattern = new RegExp('^' + conditions[i][2], 'i');
			} else if(conditions[i][1] == '$=') {
				pattern = new RegExp(conditions[i][2] + '$', 'i');
			} else if(conditions[i][1] == '%=') {
				pattern = new RegExp(conditions[i][2], 'i');
			} else if(conditions[i][1] == '~=') {
				pattern = new RegExp('(^|[ ])' + conditions[i][2] + '([ ]|$)', 'i');
			}
			var v = attr(o, conditions[i][0]);
			if(pattern && !pattern.test(v)) {
				r = false;
				break;
			}
		}
		return r;
	});
	return this;
};

query.prototype.size = function(){
	return this.elements.length;
};

query.prototype.get = function(i) {
	return typeof i == "number" ? this.elements[i] : this.elements;
}

var f = ["prev", "next", "first", "last", "parent", "children", "text", "html", "val", "attr", "before", "remove", "append", "position", "getStyle", "setStyle", "css", "height", "width", "hasClass", "addClass", "removeClass", "hide", "show", "fadeIn", "fadeOut", "slide", "gradient", "addEvent", "removeEvent"];
for (var i=0; i<f.length ; i++ ){
	(function(){
		var name = f[i];
		query.prototype[name] = function(){
			var arg = [this.elements[0]];
			for (var i=0, L=arguments.length; i<L ; i++ )
				arg.push(arguments[i]);

			return window[name].apply(this, arg) || this;
		};
	})();
}

var f = ["map", "grep"];
for (var i=0; i<f.length ; i++ ){
	(function(){
		var name = f[i];
		query.prototype[name] = function(){
			var arg = [this.elements];
			for (var i=0, L=arguments.length; i<L ; i++ )
				arg.push(arguments[i]);

			return window[name].apply(this, arg) || this;
		};
	})();
}

})();